<template>
    <div>
        <el-dialog :title="props.isAdd ? '添加商品规格' : '编辑商品规格'" v-model="props.isShow" center :before-close="beforeClose">
            <el-form :model="specssFrom" :rules="rules" ref="specssRef">
                <el-form-item label="规格名称" :label-width="formLabelWidth" prop="specsname">
                    <el-input v-model="specssFrom.specsname" autocomplete="off" />
                </el-form-item>
                <el-form-item v-for="(domain, index) in dynamicValidateForm.domains" :key="domain.key" label="规格属性"
                    :label-width="formLabelWidth">
                    <el-col :span="16"><el-input v-model="domain.value" /></el-col>
                    <el-button @click="addDomain" v-if="index == 0">新增规格属性</el-button>
                    <el-button type="danger" plain @click.prevent="removeDomain(domain)" v-else>删除</el-button>
                </el-form-item>
                <!-- <el-form-item v-for="(item, index) in attrArr.data" :key="item.id" label="规格属性"
                    :label-width="formLabelWidth">
                    <el-col :span="16"><el-input v-model="item.value" /></el-col>
                    <el-button @click="addArr" v-if="index == 0">新增规格属性</el-button>
                    <el-button type="danger" plain @click.prevent="del(index)" v-else>删除</el-button>
                </el-form-item> -->
                <el-form-item label="状态" :label-width="formLabelWidth">
                    <el-switch v-model="specssFrom.status"
                        style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949" :active-value="1"
                        :inactive-value="2" />
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="cancel(specssRef)">取消</el-button>
                    <el-button type="primary" @click="sure(specssRef)">确定</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>
<script lang='ts' setup>
import { defineProps, defineEmits, ref, reactive, defineExpose } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage } from 'element-plus'
import { specsAdd, specsEdit, specsInfo } from '../../request/api'
import { useStore } from 'vuex'
let store = useStore()

//父传子 接收数据
let props = defineProps({
    isShow: Boolean,
    isAdd: Boolean
})

//子传父
let emit = defineEmits(['cancel'])

let newId = 0

//表单对象
let specssFrom = ref<any>({
    specsname: '',//商品规格名称string’颜色‘
    attrs: '',//商品规格属性值string"白色,红色，黄色"
    status: 1,//状态1正常2禁用number1
})

//封装一个确定事件
let specssRef = ref<FormInstance>()

//关闭x事件
const beforeClose = (done: any) => {
    done()
    cancel(specssRef.value)
}

//封装一个取消事件
const cancel = (formEl?: FormInstance | undefined) => {
    emit('cancel', false)
    if (!formEl) return
    specssFrom.value = {
        specsname: '',//商品规格名称string’颜色‘
        attrs: '',//商品规格属性值string"白色,红色，黄色"
        status: 1,//状态1正常2禁用number1
    }
    //清除表单验证
    formEl.resetFields()
    dynamicValidateForm.domains = [
        {
            key: 1,
            value: '',
        }
    ]
    // attrArr.data = []
}

//确定事件
const sure = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.validate((val) => {
        if (val) {
            //通过数组方法 map 映射
            specssFrom.value.attrs = dynamicValidateForm.domains.map((item: any) => item.value).join(',')
            // specssFrom.value.attrs = attrArr.data.map((item: any) => item.value).join(',')
            if (props.isAdd) {
                // console.log(specssFrom.value, 222);
                specsAdd(specssFrom.value).then(res => {
                    if (res.code == 200) {
                        console.log(res, 1111);
                        ElMessage({
                            message: res.msg,
                            type: 'success',
                        })
                        store.dispatch('specss/getSpecssListActions')
                        store.dispatch('specss/getSpecssCount')
                        cancel(formEl)
                    } else {
                        ElMessage.error(res.msg)
                    }
                })
            } else {
                specsEdit({ ...specssFrom.value, id: newId }).then(res => {
                    if (res.code == 200) {
                        console.log(res, 1111);
                        ElMessage({
                            message: res.msg,
                            type: 'success',
                        })
                        store.dispatch('specss/getSpecssListActions')
                        cancel(formEl)
                    } else {
                        ElMessage.error(res.msg)
                    }
                })
            }
        }
    })
}

//规则验证
const rules = reactive<FormRules>({
    specsname: [
        { required: true, message: '请输入菜单名称', trigger: 'blur' },
        { min: 2, max: 8, message: '长度为2-8个字符', trigger: 'blur' },
    ]
})


// const attrArr = reactive<any>({ data: [] })
const dynamicValidateForm = reactive<{
    domains: DomainItem[]
    email: string
}>({
    domains: [
        {
            key: 1,
            value: '',
        },
    ],
    email: '',
})

interface DomainItem {
    key: number
    value: string
}


const removeDomain = (item: DomainItem) => {
    const index = dynamicValidateForm.domains.indexOf(item)
    if (index !== -1) {
        dynamicValidateForm.domains.splice(index, 1)
    }
}

const addDomain = () => {
    if (dynamicValidateForm.domains.length > 6) {
        ElMessage.warning('最多添加6条')
        return
    }
    dynamicValidateForm.domains.push({
        key: Date.now(),
        value: '',
    })
}

//数据回显
const lookup = (id: number) => {
    specsInfo({ id }).then((res: any) => {
        // console.log(id);    
        specssFrom.value = res.list[0]
        newId = id
        specssFrom.value.attrs.map((domain: any, index: any) => {
            console.log(domain, '111');
            if (index == 0) {
                dynamicValidateForm.domains[0].value = domain
            } else {
                dynamicValidateForm.domains.push({
                    value: domain,
                    key: Date.now()
                })
            }
        })
    })
}

defineExpose({
    lookup
})

// const addArr = () => {
//     if (attrArr.length > 6) {
//         ElMessage.warning('最多6条数据,不能在多了')
//         return
//     }
//     attrArr.push({
//         data: ''
//     })
// }

// //删除
// const del = (index: any) => {
//     attrArr.data.splice(index, 1)
// }

// const lookup = (id:number) =>{
//     specsInfo({id}).then((res:any)=>{
//         if(res.code == 200){
//             specssFrom.value = res.list[0]
//             newId = id
//             specssFrom.value.attrs.map((item: any,index: number)=>{
//                 if(index == 0){
//                     attrArr[0].data = item
//                 }else{
//                     attrArr.data.push({

//                     })
//                 }
//             })
//         }
//     })
// }

// defineExpose({
//     lookup
// })
const formLabelWidth = '140px'
</script>
<style lang='less' scoped></style>